package com.winner.kettle.controller;

import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * 使用的是kettle的pdi-ce-9.0.0.0-423版本, 开发的 ktr/kjb 脚本, 需要将pdi-ce-9.0.0.0-423安装目录的lib文件夹的必要的jar放到本项目中.
 * https://blog.csdn.net/pingweicheng/article/details/103547943
 *
 * @Author wangxinle5
 * @since 2024-03-26
 */
@Slf4j
@RestController
public class KettleController {

    /**
     * 一般来说, 直接运行转换ktr文件就可以完成ETL, 结合XXL-Job的定时任务就可以了
     *
     * localhost:8080/transfer
     */
    @GetMapping("/transfer")
    public void kettle()  {
        try {
            // init() 代码可以写到项目启动时初始化
//            KettleEnvironment.init();
            String ktrFilePath = ResourceUtils.getURL("classpath:user.ktr").getPath();
            TransMeta tm = new TransMeta(ktrFilePath);
            Trans trans = new Trans(tm);
            trans.execute(null);
            trans.waitUntilFinished();
            log.info("转换执行成功");
        } catch (Exception e) {
            log.error("转换执行失败, 错误信息是{}", e.getMessage());
        }

    }


    /**
     * localhost:8080/job  新建的作业,用的是D盘的,那么保存作业到springboot项目里D盘没有这个转换,就会报错
     * The transformation path D:/user.ktr is invalid, and will not run successfully.
     */
    @GetMapping("/job")
    public void job()  {
        try {
            // init() 代码可以写到项目启动时初始化
//            KettleEnvironment.init();
            String kjbFilePath = ResourceUtils.getURL("classpath:user.kjb").getPath();
            JobMeta jm = new JobMeta(kjbFilePath, null);
            Job job = new Job(null, jm);
            job.start();
            job.waitUntilFinished();
            log.info("作业执行成功");
        } catch (Exception e) {
            log.error("作业执行失败, 错误信息是{}", e.getMessage());
        }
    }
}
